<?php
namespace app\controller;

use support\Db;
use support\Request;

class FgController
{
    public function style()
    {
        $data = Db::table('wa_fg_style')->select()->get()->toArray();

        return json(['code' => 0, 'msg' => 'succ', 'data' => $data]);
    }

    public function testdb(Request $request)
    {

        $user = Db::table('wa_fg_admins')->select();

        return json(['code' => 0, 'msg' => $user]);
    }

    public function upload(Request $request)
    {
        $styleId = $request->input('styleId');
        Db::table('wa_fg_style')->where('id', $styleId)->increment('hot', 1);

        $file = current($request->file());
        if (!$file || !$file->isValid()) {
            return json(['code' => 1, 'msg' => '未找到文件', 'data' => []]);
        }

        $img_exts = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($file->getUploadExtension(), $img_exts)) {
            return json(['code' => 2, 'msg' => '文件格式不支持', 'data' => []]);
        }

        $relative_path = '/task/' . date('Ym');
        $real_path     = base_path() . '/public' . $relative_path;
        if (!is_dir($real_path)) {
            mkdir($real_path, 0755, true);
        }

        $ext       = $file->getUploadExtension() ?: '';
        $mime_type = $file->getUploadMimeType();
        $file_name = $file->getUploadName();
        $file_size = $file->getSize();

        $name = bin2hex(pack('Nn', time(), random_int(1, 65535))) . ".$ext";
        $file->move($real_path . '/' . $name);

        return json(['code' => 0, 'msg' => '上传成功', 'data' => [
            'url'  => 'https://' . $request->header('host') . $relative_path . '/' . $name,
            'size' => $file_size,
        ]]);
    }

    public function login(Request $request)
    {
        $from      = $request->input('from');
        $code      = $request->input('code');
        $env       = $request->input('env');
        $appid     = config('key.FG_APPID');
        $appsecret = config('key.FG_APPSECRET');

        if ($env == 'development') {
            $res['openid'] = 'abc123456789';
        } else {
            $res = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code");
            $res = json_decode($res, true);
        }

        $user = Db::table('wa_fg_user')->where('openid', $res['openid'])->first();
        if (!$user) {
            $user = [
                'openid'      => $res['openid'],
                'coin'        => 1,
                'create_time' => time(),
            ];
            Db::table('wa_fg_user')->insert($user);

            if ($from) {
                Db::table('wa_fg_invite_log')->insert(['openid' => $from, 'to' => $res['openid'], 'time' => time()]);

                $count = Db::table('wa_fg_invite_log')->where('openid', $from)->count();
                if ($count) {
                    $reward = getReward($count+1);
                    if ($reward) {
                        Db::table('wa_fg_user')->where('openid', $from)->increment('coin', $reward);
                    }
                }

            }
        }

        $share = [
            'title'    => '太炸了！我的照片被AI改造后...',
            'desc'     => '🔥🔥🔥朋友圈都在问怎么弄的',
            'path'     => '/pages/index/index?from=' . $res['openid'],
            'imageUrl' => 'https://web.h5sdk.com/common/fg/share.jpg',
        ];

        return json(['code' => 0, 'msg' => '登录成功', 'data' => $user, 'share' => $share]);
    }

    public function generateImage(Request $request)
    {
        $openid = $request->header('X-token');
        $count  = $request->input('selectedCount');

        $user = (array) Db::table('wa_fg_user')->where('openid', $openid)->first();

        if (!$user) {
            return json(['code' => -1, 'msg' => '识别用户失败']);
        }

        if ($user['coin'] < $count) {
            return json(['code' => 999, 'msg' => '金币不足，观看视频可增加金币哦~']);
        }

        $generateSize = getImageSizeConfig($request->input('selectedAspectRatio'), $request->input('uploadedImage'));
        if ($request->input('action') == 'i2i_portrait_photo') {
            $response = CVSync2AsyncTask($request->input('uploadedImage'), $request->input('promptText'), $request->input('mode'), $generateSize);

            if ($response['code'] == 10000) {
                Db::table('wa_fg_task')->insert([
                    'openid'  => $openid,
                    'task_id' => $response['data']['task_id'] ?? '',
                    'message' => "{$response['code']}:{$response['message']}",
                    'status'        => $response['code'] == 10000 ? 0 : 2,
                    'uploadedImage' => $request->input('uploadedImage'),
                    'promptText'    => $request->input('promptText'),
                    'style_id'      => $request->input('id'),
                    'create_time'   => time(),
                ]);
                Db::table('wa_fg_user')->where('openid', $openid)->decrement('coin', $count);
                return json(['code' => 0, 'msg' => '提交成功，请稍等片刻在转换记录查看', 'data' => ['coin' => (int) $user['coin'] - (int) $count]]);
            } else {
                return json(['code' => -1, 'msg' => "{$response['code']}:{$response['message']}"]);
            }
        }

    }

    public function getRecord(Request $request)
    {
        $openid = $request->header('X-token');
        $status = $request->input('status');

        $where[] = ['wa_fg_task.openid', '=', $openid];

        if ($status == 1) {
            $where[] = ['wa_fg_task.status', '=', 1];
        } elseif ($status == 2) {
            $where[] = ['wa_fg_task.status', '=', 0];
        } else {
            $where[] = ['wa_fg_task.status', '<', 2];
        }

        $data = Db::table('wa_fg_task')
            ->where($where)
            ->leftJoin('wa_fg_style', 'wa_fg_task.style_id', '=', 'wa_fg_style.id')
            ->select('wa_fg_task.*', 'wa_fg_style.style', Db::raw('FROM_UNIXTIME(`wa_fg_task`.`create_time`, "%Y-%m-%d %H:%i:%s") as create_time'))
        //->toSql();
            ->get()->toArray();

        return json(['code' => 0, 'msg' => '', 'data' => $data]);
    }

    public function getInviteLog(Request $request)
    {
        $openid = $request->header('X-token');
        $status = $request->input('status');

        $count = Db::table('wa_fg_invite_log')
            ->where([['openid', '=', $openid]])
            ->count();

        $data = getReward();

        foreach ($data as &$v) {
            if ($count >= $v['count']) {
                $v['completed'] = true;
            }
        }

        return json(['code' => 0, 'msg' => '', 'count' => $count, 'data' => $data]);
    }

    public function getAdLog(Request $request)
    {
        $openid = $request->header('X-token');
        $status = $request->input('status');

        $count = Db::table('wa_fg_ad_log')
            ->where([['openid', '=', $openid], ['type', '=', 1], ['time', '>=', strtotime('today midnight')]])
            ->count();

        $data = getReward();

        foreach ($data as &$v) {
            if ($count >= $v['count']) {
                $v['completed'] = true;
            }
        }
        return json(['code' => 0, 'msg' => '', 'data' => $data]);
    }

    public function delImg(Request $request)
    {
        $openid = $request->header('X-token');
        $id     = $request->input('id');

        Db::table('wa_fg_task')
            ->where([['openid', '=', $openid], ['id', '=', $id]])
            ->update(['status' => 2]);

        return json(['code' => 0, 'msg' => 'succ']);
    }

    public function watchAd(Request $request)
    {
        $openid = $request->header('X-token');
        if (!$openid) {
            return json(['code' => -1, 'msg' => 'error']);
        }

        $count = Db::table('wa_fg_ad_log')
            ->where([['openid', '=', $openid], ['type', '=', 1], ['time', '>=', strtotime('today midnight')]])
            ->count();

        $reward = getReward($count + 1);
        if ($reward) {
            Db::table('wa_fg_user')->where('openid', $openid)->increment('coin', $reward);
        }

        $user = (array) Db::table('wa_fg_user')->where('openid', $openid)->first();

        return json(['code' => 0, 'msg' => 'succ', 'data' => $user['coin']]);
    }
}
